package eerbaar.shared.tree;

public class DefaultPayload implements IPayload {

    private final String key;

    private final int mergeCount;

    private final String value;

    public DefaultPayload(DefaultPayload p1, DefaultPayload p2) {
        assert (p1.key.equals(p2.key));
        assert (p1.value.equals(p2.value));

        this.key = p1.key;
        this.value = p1.value;
        this.mergeCount = p1.mergeCount + p2.mergeCount + 1;
    }

    public DefaultPayload(IPayload payload) {
        assert (payload != null);

        this.key = payload.getKey();
        this.value = payload.getValue();
        this.mergeCount = payload.getMergeCount();
    }

    public DefaultPayload(String key) {
        assert (key != null);

        this.key = key;
        this.value = "";
        this.mergeCount = 0;
    }

    public DefaultPayload(String key, String value) {
        assert (key != null);
        assert (value != null);

        this.key = key;
        this.value = value;
        this.mergeCount = 0;
    }

    public DefaultPayload(String key, String value, int mergeCount) {
        assert (key != null);
        assert (value != null);

        this.key = key;
        this.value = value;
        this.mergeCount = mergeCount;
    }

    @Override
    public IPayload copy() {
        return new DefaultPayload(this);
    }

    @Override
    public boolean equals(Object obj) {

        IPayload other = (IPayload) obj;
        boolean b1 = (other.getKey().equals(this.key));
        boolean b2 = (other.getValue().equals(this.value));
        return (b1 && b2);
    }

    @Override
    public String getKey() {

        return this.key;
    }

    @Override
    public int getMergeCount() {

        return this.mergeCount;
    }

    @Override
    public String getValue() {

        return this.value;
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public String toString() {

        String result = this.key;
        if (this.value.length() > 0) {
            result += "->" + this.value;
        }
        if (this.mergeCount > 0) {
            result += "(" + this.mergeCount + ")";
        }

        return result;
    }

}
